package cn.fl.project.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.condition.PrjPrdPaySchMQueryCondition;
import cn.fl.project.service.IPrjContService;
import cn.fl.project.service.IPrjPrdPaySchMService;
import cn.fl.project.transform.PrjContSignDetailVOTransform;
import cn.fl.project.vo.PrjContSignDetailVO;
import cn.fl.project.vo.PrjPrdPaySchMVO;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import tc.esign.facade.esign.api.ICfcaUsrApiService;
import tc.esign.facade.esign.api.IFilSignApiService;
import tc.esign.facade.esign.api.IFilSignInfoApiService;
import tc.esign.facade.esign.condition.CfcaUsrQueryCondition;
import tc.esign.facade.esign.condition.FilSignInfoQueryCondition;
import tc.esign.facade.esign.condition.FilSignQueryCondition;
import tc.esign.facade.esign.dto.CfcaUsrDTO;
import tc.esign.facade.esign.dto.FilSignDTO;
import tc.esign.facade.esign.dto.FilSignInfoDTO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/project/cont")
public class PrjContController extends BaseController{

	private static final Logger logger = LoggerFactory.getLogger(PrjContController.class);

	@Autowired
	private IFilSignApiService filSignApiService;
	
	@Autowired
	private IFilSignInfoApiService filSignInfoApiService;
	
	@Autowired
	private ICfcaUsrApiService cfcaUsrApiService;
	
    /**
     * 支付表服务
     */
    @Autowired
    private IPrjPrdPaySchMService prjPrdPaySchMService;
    
    /**
     * 项目合同服务
     */
    @Autowired
    private IPrjContService prjContService;
	
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		String prjId = request.getParameter("prjId");
		String detailFlag = request.getParameter("detailFlag");
		ModelAndView view = new ModelAndView("project/prjcont/prjContList");
		view.addObject("prjId", prjId);
		view.addObject("detailFlag", detailFlag);
			//融资外部机构专用
		view.addObject("pianflag",request.getParameter("pianflag"));
		//********流程参数开始********//
		String preTaskIds = request.getParameter("preTaskIds");//流程上一个节点任务ID,多个以逗号分割.
		String pInstId = request.getParameter("pInstId");//流程实例ID
		view.addObject("pInstId", pInstId);
		view.addObject("preTaskIds", preTaskIds);
		//********流程参数结束********//
		
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String prjId = request.getParameter("prjId");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		
		List<Long> filIdList = new ArrayList<>();
		filIdList.add(Long.valueOf(prjId));
		try {
			PrjPrdPaySchMQueryCondition prjPrdPaySchMQueryCondition = new PrjPrdPaySchMQueryCondition();
			prjPrdPaySchMQueryCondition.setPrjId(Long.valueOf(prjId));
			List<PrjPrdPaySchMVO> prjPrdPaySchMVOList = this.prjPrdPaySchMService.searchList(prjPrdPaySchMQueryCondition);
			if(CollectionUtils.isNotEmpty(prjPrdPaySchMVOList)){
				for (PrjPrdPaySchMVO prjPrdPaySchMVO : prjPrdPaySchMVOList) {
					filIdList.add(prjPrdPaySchMVO.getId());
				}
			}
		} catch (Exception e) {
			BaseLogUtils.error(logger, "initList", "获取支付表ID失败", e);
		}

		if(CollectionUtils.isEmpty(filIdList)){
			filIdList.add(0L);
		}
		FilSignQueryCondition qc = new FilSignQueryCondition();
		qc.setFilIdList(filIdList);
		page.setCondition(qc);
		Pager pager = null;
		try {
			pager = this.filSignApiService.searchListPage(page);
		} catch (Exception e) {
			BaseLogUtils.error(logger, "initList", "获取电子合同列表失败", e);
		}
		BaseLogUtils.info(logger, "initList", "==C==");
		List<FilSignDTO> list = (List<FilSignDTO>) pager.getResultList();
		ListPageVO<FilSignDTO> listPage=null;
		if ("101".equals(request.getParameter("pianflag"))) {			
			for (int i = 0; i < list.size(); i++) {
				if (!(list.get(i).getContractNm().contains("买卖合同") 
						|| list.get(i).getContractNm().contains("融资租赁合同") 
						|| list.get(i).getContractNm().contains("租赁支付表"))) {
					list.remove(i);
					i--;
				}
			}
			 listPage = new ListPageVO<FilSignDTO>(list, list.size());
		}else {
			 listPage = new ListPageVO<FilSignDTO>(list, pager.getTotalCount());
		}
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	
	
	/**
	 * 获取合同详细列表数据
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/searchDetailList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object searchDetailList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String filSignId = request.getParameter("filSignId");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		FilSignInfoQueryCondition qc = new FilSignInfoQueryCondition();
		
		if(StringUtils.isNotBlank(filSignId)){
			qc.setFilSignId(Long.valueOf(filSignId));
		}
		page.setCondition(qc);

		Pager pager = this.filSignInfoApiService.searchListPage(page);
		pager.setResultList(PrjContSignDetailVOTransform.toVOList((List<FilSignInfoDTO>)pager.getResultList()));
        List<PrjContSignDetailVO> list = (List<PrjContSignDetailVO>)pager.getResultList();
		if (CollectionUtils.isNotEmpty(list)){
			 for(PrjContSignDetailVO vo: list){
				 String userId = vo.getUserId();
				 if(StringUtils.isNotBlank(userId)) {
					 CfcaUsrQueryCondition cfcaUsrQueryCondition = new CfcaUsrQueryCondition();
					 cfcaUsrQueryCondition.setUserId(userId);
					 List<CfcaUsrDTO> usrDto = this.cfcaUsrApiService.getListByQc(cfcaUsrQueryCondition);
					 if (usrDto != null && usrDto.size() > 0) {
						 vo.setSignName(usrDto.get(0).getUserNm());
						 vo.setSignNm(usrDto.get(0).getMobilePhone());
					 }
				 }
				 if("1".equals(vo.getSignSts()+"")){
					 vo.setSignStsName("已签署");
				 }else{
					 vo.setSignStsName("未签署");
				 }
			 }
		}
		
		ListPageVO<PrjContSignDetailVO> listPage = new ListPageVO<PrjContSignDetailVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "searchDetailList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	
	/**
	 * 重新生成合同
	 */
	@RequestMapping(value = "/reCreateCont.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object reCreateCont(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		String contId = request.getParameter("contId");
		String filId = request.getParameter("filId");
		//String signSts = request.getParameter("signSts");
		if(StringUtils.isEmpty(contId)){
			BaseLogUtils.info(logger, "reCreateCont", "合同ID不能为空!" , CurrentThreadContext.getCurrentUserName());
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("合同ID不能为空!");
			return result;
		}
		
		if(StringUtils.isEmpty(filId)){
			BaseLogUtils.info(logger, "reCreateCont", "业务主键不能为空!" , CurrentThreadContext.getCurrentUserName());
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("业务主键不能为空!");
			return result;
		}
		
		try {
			this.prjContService.modifyContPDFByPkIdAndOlContId(filId, contId);
			BaseLogUtils.info(logger, "reCreateCont", "操作数据. DATA:" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "reCreateCont", "操作失败[BaseException].DATA:" + this.getRequestParameter(request) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "reCreateCont", "操作失败[Exception].DATA:" + this.getRequestParameter(request) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 作废合同
	 */
	@RequestMapping(value = "/delCont.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object delCont(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		String contId = request.getParameter("contId");
		String filId = request.getParameter("filId");
		if(StringUtils.isEmpty(contId)){
			BaseLogUtils.info(logger, "reCreateCont", "合同ID不能为空!" , CurrentThreadContext.getCurrentUserName());
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("合同ID不能为空!");
			return result;
		}
		if(StringUtils.isEmpty(filId)){
			BaseLogUtils.info(logger, "reCreateCont", "业务主键不能为空!" , CurrentThreadContext.getCurrentUserName());
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("业务主键不能为空!");
			return result;
		}
		try {
			this.prjContService.delContPDFByPkIdAndOlContId(filId, contId);
			BaseLogUtils.info(logger, "delCont", "操作数据. DATA:" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "delCont", "操作失败[BaseException].DATA:" + this.getRequestParameter(request) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "delCont", "操作失败[Exception].DATA:" + this.getRequestParameter(request) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
}
